#include "../util/TcpListener.h"
#include "Dsm.h"

 
extern "C" {
  #include <sys/time.h>
}
 
void usage() {
  cout << "Usage: DsmTimeClient <name-server-port> " << endl;
  exit(1);
}
 

// Evaluable 3.3.5. (6)

int main(int argc, char** argv) {
        if (argc > 2) {
                usage();
        }
 
        PracticaCaso::DsmDriver * driver = new PracticaCaso::DsmDriver("127.0.0.1", atoi(argv[1]), "dsm.deusto.es");
        PracticaCaso::DsmData data;
        cout << "Node created with NID: " << driver->get_nid() << endl;
		
		int tempMAX = 900;
		int tempMIN = 100;
		char bufferError[6] = "error";
		
        while (1) {
               
         bool cond = false;
         while (!cond) {
            try {
                data = driver->dsm_get("ENVIRONMENT_TEMPERATURE");
                cond = true;
               } catch (DsmException excepcion) {
                cerr << "ERROR getting ENVIRONMENT_TEMPERATURE: " << excepcion  << endl;
                driver->dsm_wait("ENVIRONMENT_TEMPERATURE");
              }
		     }
			char* temp;
			temp = ((char *)data.addr);
			int temperatura = atoi (temp);
			cout << temperatura << endl;
			
			if (temperatura < tempMIN) {
			cout << "WARNING! The temperature:   " << temperatura << " is below the permitted"<< endl;
			cout << "Inject fuel in the heater" << endl;
			sleep(4);
			} else if (temperatura > tempMAX) {
			cout << "WARNING!!! The temperature:   " << temperatura << " is above the permitted"<< endl;
			cout << "System is turning OFF!" << endl;
			try {			
            driver->dsm_put("ALERT", (void *)bufferError, sizeof(bufferError));	
			exit(1);
			} catch (DsmException excepcion) {
            cerr << "ERROR setting ALERT: " << excepcion << endl;
            driver->dsm_free("ALERT");
            exit(1);
			}
			} else {
			cout << "Stay calm. Everything is under control:   " << temperatura <<endl;
			}
			sleep(1);
		}
 
}
